package com.id.coinscleaner.utils

import android.app.Activity
import com.id.coinscleaner.App.Companion.DataStore
<<<<<<< HEAD
=======
import com.id.coinscleaner.utils.ScreenshotContentResolver
import com.id.coinscleaner.utils.hasReadStoragePermission
import com.id.coinscleaner.utils.hasWriteStoragePermission
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
import com.revenuecat.purchases.*
import com.revenuecat.purchases.interfaces.PurchaseCallback
import com.revenuecat.purchases.models.StoreProduct
import com.revenuecat.purchases.models.StoreTransaction
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapConcat

private const val NoPermissionComeInOnce = "NoPermissionComeInOnce"
//TODO 改变相关sku
sealed class SubSku(val skuId: String) {
    //    object Sku1Monthly : SubSku("")
//    object Sku3Monthly : SubSku("")
//    object Sku1Yearly : SubSku("")
    object SkuYearly : SubSku("yearly_999")
    object SkuTrail:SubSku("yearly_999")
    companion object {
        fun findSubSkuBySkuId(skuId: String): SubSku = when (skuId) {
            SkuYearly.skuId -> SkuYearly
            SkuTrail.skuId -> SkuTrail
            else -> throw IllegalArgumentException("$skuId not find!")
        }

        fun findSubSkuBySkuIdOrDefault(skuId: String, default: () -> SubSku) = try {
            findSubSkuBySkuId(skuId)
        } catch (e: Throwable) {
            default()
        }
    }


}

class UserCanceledPayException : RuntimeException("user cancelled pay!")

fun isSubscribe() = callbackFlow {
    Purchases.sharedInstance.getCustomerInfoWith(onError = { close(Exception(it.message)) }) {
        trySendBlockingAndClose(it.entitlements.active.isNotEmpty())
    }
    awaitClose()
}

@OptIn(FlowPreview::class)
fun Activity.pay(subSku: SubSku) = queryOfferings(subSku).flatMapConcat { pay(it) }

private fun Activity.pay(storeProduct: StoreProduct) = callbackFlow {
    Purchases.sharedInstance.purchaseProduct(this@pay, storeProduct, object : PurchaseCallback {
        override fun onCompleted(storeTransaction: StoreTransaction, customerInfo: CustomerInfo) {
            trySendBlockingAndClose(Pair(storeTransaction, customerInfo))
        }

        override fun onError(error: PurchasesError, userCancelled: Boolean) {
            val exception =
                if (userCancelled) UserCanceledPayException() else Exception(error.message)
            close(exception)
        }
    })
    awaitClose()
}

private fun queryOfferings(sku: SubSku) = callbackFlow {
    Purchases.sharedInstance.getSubscriptionSkusWith(listOf(sku.skuId)) { items ->
        val storeProduct = items.find { it.sku == sku.skuId } ?: let {
            close(IllegalArgumentException("offering is not find"))
            return@getSubscriptionSkusWith
        }
        trySendBlockingAndClose(storeProduct)
    }
    awaitClose()
}

private fun <E> SendChannel<E>.trySendBlockingAndClose(element: E) {
    trySendBlocking(element)
    close()
}

suspend fun isEntryAlarmed(): Boolean {
    if (isSubscribe().catch { emit(false) }.first()) return false//是否订阅(网络不行直接返回false)
    if (ScreenshotContentResolver.isScreenshot) return false//是否截屏
    val hasFirst = DataStore.decodeBool(NoPermissionComeInOnce)//是否第一次进来
    if (!hasFirst) return true
    return hasWriteStoragePermission || hasReadStoragePermission//是否有读或写权限
}